var app = getApp();
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var mock = require('../../mock/mock');
var mockDetail = require('../../mock/detail');
var swiper = require('../../components/swiper/swiper');
var actionSheet = require('../../components/actionSheet/actionSheet');
var storage = require('../../utils/storage');
var goTop = require('../widget/goTop/goTop');
var comment = require('../widget/comment/comment');
var storage = require('../../utils/storage');
var commentList = require('../widget/commentList');
var timestamp = require('../widget/timestamp');
var filter = require('../widget/filter');
var formatTime = require('../widget/time');

//var actionSheetOption = {};
var mark = 0;
var pageSetting = {
    callback:function(componentName){
        console.log(componentName);
    	var that = this;
        switch(componentName){
            case 'sliderBar':
                var type = arguments[1];
                var id = arguments[2];
                this.setData({
                    wiiSliderBar:{
                        isActive:id,
                        data:this.data['wiiSliderBar']['data']
                    }
                });
            break;
            case 'sliderPanel':
                var current = arguments[1];
                wx.previewImage({
                    current: current,
                    urls: mock.imageList
                });
            break;
            case 'smsBind':
                var fn = arguments[1]
                request.bind().then(() => {
                    fn.call(this)
                })
            break;
            case 'actionSheet':
                //actionSheet提交
                var detailData = this.data['detailData']['data'];
                var counter = arguments[1];
                var type = arguments[2];
                var id = detailData['id'];
                var purchase_count = counter['countNumber'];
                var commodity_name = detailData['commodity_name'];
                var act_spec = counter['info'];
                var act_spec_id = counter['id']
                var onePrice = counter['price'];
                var totalNumber = counter['maxNumber'];
                var maxNumber = counter['maxNumber'];
                if(maxNumber <= 0){
                    modal.toast('库存量不足');
                    return false;
                }
                
                if(type == 'buy'){
                    //点击立即购买之后的回调函数
                    //点击底部bar不是购物车
                    wx.navigateTo({
                       url: '../order-detail/order-detail?cart_id=0&act_id='+id+'&type='+act_spec_id+'&num='+purchase_count+'&p_time='+detailData['presell_time']+'&sell_type='+detailData['sell_type']+'&sales_form='+detailData['sales_form']+'&offline_order_address='+detailData['offline_order_address']+'&offline_order_user='+detailData['offline_order_user']+'&offline_order_phone='+detailData['offline_order_phone']+'&offline_share_link='+detailData['offline_share_link']+
                           '&offline_province_id='+detailData['offline_province_id']+
                           '&offline_city_id='+detailData['offline_city_id']+
                           '&offline_area_id='+detailData['offline_area_id']
                       // url: '../order-detail/order-detail?act_id=' +id+ '&onePrice=' +onePrice+ '&totalNumber=' +totalNumber+ '&purchase_count=' +purchase_count + '&act_spec=' +act_spec+ '&name=' + commodity_name+ '&shipping_id='+this.data['shipping_id']+'&shipping='+this.data['shipping']+'&p_time='+detailData['presell_time']+'&sell_type='+detailData['sell_type']
                    })
                }else if(type == 'cart'){
                //点击加入购物车之后的回调函数
		           	// modal.loading();
                    app.globalData.cartCountState = true;
                    app.globalData.cartNumState = true;
                    request.post({
			        	path:'/wxapp_api/api'
			            },{'dp:api:act:cartsave':{"purchase_count":purchase_count,"act_spec_id":act_spec_id,"act_spec":act_spec,"act_id":id,"selected":1}})
			            .then(function(res){
			        		var cartsaveData=res['dp:api:act:cartsave'];
			        	    if(cartsaveData.ret==0){
                                // modal.hide();
                                wx.showToast({
                                    title: '加入购物车',
                                    icon: 'success',
                                    duration: 2000
                                })
			        	    	var cartCount = Number(that['data']['cartCount']) + Number(purchase_count);
			        	    	that.setData({
			        	    		cartCount : cartCount
			        	    	});
			               }
		            });
       			}
            break;
            case 'actionSheetTap':
                //actionSheet点击
                var choosedSku = this.data['wiiActionSheet']['data']['choosedSku'];
                var skuList = this.data['wiiActionSheet']['data']['skuList'];
                var counter = this.data['wiiActionSheet']['counter']['wiiCounter']['data'];

                // 组件有bug，切换之后 wiiActionSheet.data.choosedSku.minNumber和maxNumber没有更新，手动fix
                var id = choosedSku.id;
                var minNumber, maxNumber;
                for(var k in skuList){
                    if(skuList[k].id == id){
                        minNumber = skuList[k].minNumber;
                        maxNumber = skuList[k].maxNumber;
                        break;
                    }
                }
                this.setData({
                    'wiiActionSheet.data.choosedSku.minNumber': minNumber,
                    'wiiActionSheet.data.choosedSku.maxNumber': maxNumber
                });
                
                // 组件有bug，切换之后 wiiActionSheet.counter 没有更新，手动fix
                this.setData({
                    'detailData.data.act_spec': choosedSku['name'],
                    'wiiActionSheet.data.prePrice': choosedSku['prePrice'],
                    'wiiActionSheet.counter.wiiCounter.data': {
                        minNumber: 1,
                        maxNumber: (+choosedSku.maxNumber) < 1 ? 1 : (+choosedSku.maxNumber),
                        countNumber: (+counter.countNumber) > (+choosedSku.maxNumber) ? ((+choosedSku.maxNumber) === 0 ? 1 : (+choosedSku.maxNumber)) : (+counter.countNumber),
                        isMin: (+choosedSku.maxNumber) <= 1 || (+counter.countNumber) <= 1,
                        isMax: (+counter.countNumber) >= (+choosedSku.maxNumber),
                        numberUnit: 1
                    }
                });
            break;
            case 'commentContent':
                var commentData = that.data['commentData'];
                commentFun(commentData, arguments[1]);
            break;
            case 'likeFun':
                var likeData = arguments[1];
                like(likeData);
            break;
            case 'delcommentFun':
                var delData = arguments[1];
                delcommentFun(delData);
            break;
            case 'removeBindtapFun':
                var removeFlag = arguments[1];
                removeBindtapFun(removeFlag);
            break;
            case 'delStairComment':
                delStairComment(arguments[1]);
            break;
            case 'delSecondComment':
                delSecondComment(arguments[1]);
            break;
              case 'pullUpLoad':
                pullUpLoad();
            break;
              case 'onCommentShow':
                removeBindtapFun({
                  'removebindtap': 1
                });
            break;
            default:
            break;
        }
        /* 增加评论后
        @param commentData  评论的上下文 相关信息
        @param commentContent 评论的文本内容
        */
        function commentFun(commentData, content) {
          var data = {};
          if (commentData['type'] == 1) {
            data = {
              'self:community_api:community:comment': {
                'articleId': commentData['articleid'],
                'content': content,
                'commentType': 0,
                'parentUserId': commentData['parentuserid'],
                'parentCommentId': commentData['parentcommentid'],
                'pParentCommentId': commentData['pparentcommentid'],
                'relateInfo': '',
                'timestamp': timestamp['timestamp'],
                'gtk': timestamp['gtk'],
                'come_from': 'dp_order'
              }
            }
          } else if (commentData['type'] == 2) {
            data = {
              'self:community_api:community:comment': {
                'articleId': commentData['articleid'],
                'content': content,
                'commentType': commentData['commenttype'],
                'parentUserId': commentData['parentuserid'],
                'parentCommentId': commentData['parentcommentid'],
                'pParentCommentId': commentData['pparentcommentid'],
                'relateInfo': commentData['relateinfo'],
                'relatePPInfo': commentData['relateppinfo'],
                'relatePPAccount': commentData['relateppaccount'],
                'id': commentData['id'],
                'relatePPAccountType': commentData['relateppaccounttype'],
                'timestamp': timestamp['timestamp'],
                'gtk': timestamp['gtk'],
                'come_from': 'dp_order'
              }
            }
          } else {
            data = {
              'self:community_api:community:comment': {
                'articleId': commentData['articleid'],
                'content': content,
                'commentType': commentData['commenttype'],
                'parentUserId': commentData['parentuserid'],
                'parentCommentId': commentData['parentcommentid'],
                'pParentCommentId': commentData['pparentcommentid'],
                'relateInfo': commentData['relateinfo'],
                'relatePPInfo': commentData['relateppinfo'],
                'relatePPAccount': commentData['relateppaccount'],
                'id': commentData['id'],
                'relatePPAccountType': commentData['relateppaccounttype'],
                'relatePInfo': commentData['relatepinfo'],
                'relatePAccount': commentData['relatepaccount'],
                'relatePAccountType': commentData['relatepaccounttype'],
                'timestamp': timestamp['timestamp'],
                'gtk': timestamp['gtk'],
                'come_from': 'dp_order'
              }
            }
          }

          request.post({
            path: '/wxapp_api/api'
          }, data)
            .then(function (res) {
              if (!!res['self:community_api:community:comment']['ret']) {
                modal.toast(res['self:community_api:community:comment']['msg']);
                return false;
              }
              var returnComment = res['self:community_api:community:comment']['data'];
              if (commentData['type'] == 1) {
                //一级留言
                //重新加载表评论列表
                that.loadComment({
                  articleId: commentData.articleid,
                  page: 1
                }, {}, true);
                return true;
              } else if (commentData['type'] == 2) { //二级留言            
                var newComment = commentList.commentList(returnComment, commentData);
                if (!that['data']['commentList'][commentData.index]['secondCommentInfo']['commentInfo']) {
                  that['data']['commentList'][commentData.index]['secondCommentInfo'] = {
                    'hasNext': 0,
                    'commentInfo': [newComment]
                  }
                  that['data']['commentList'][commentData.index]['commentCount'] += 1;
                } else {
                  that['data']['commentList'][commentData.index]['secondCommentInfo']['commentInfo'].push(newComment);
                  that['data']['commentList'][commentData.index]['commentCount'] += 1;
                }

              } else { //三级留言            
                var returnComment = res['self:community_api:community:comment']['data'];
                var newComment = commentList.commentList(returnComment, commentData);
                that.data.commentList[commentData.index]['secondCommentInfo']['commentInfo'].push(newComment);
                that.data.commentList[commentData.index]['commentCount'] += 1;
              }
              that.data.articleInfo.commentCount += 1;
              that.setData({
                articleInfo: that.data.articleInfo,
                commentList: that.data.commentList
              });
            })
        }

        //点赞功能
        function like(data) {
          if (data['liketabflag'] != 0) {
            return false;
          }
          that.data.commentList[data.index]['likeTabFlag'] = 1;
          that.setData({
            commentList: that.data.commentList
          });
          var likeData = {};
          if (data['type'] == -1) {
            likeData = {
              'self:community_api:community:like': {
                'articleId': data['articleid'],
                'commentId': data['commentid'],
                'likeType': data['type'],
                'id': data['id'],
                'timestamp': timestamp['timestamp'],
                'come_from': 'dp_order',
                'gtk': timestamp['gtk']
              }
            }
          } else {
            likeData = {
              'self:community_api:community:like': {
                'articleId': data['articleid'],
                'commentId': data['commentid'],
                'likeType': data['type'],
                'relateInfo': data['relateinfo'],
                'relateAccount': data['relateaccount'],
                'id': data['id'],
                'relateAccountType': data['relateaccounttype'],
                'timestamp': timestamp['timestamp'],
                'come_from': 'dp_order',
                'gtk': timestamp['gtk']
              }
            }
          }

          request.post({
            path: '/wxapp_api/api'
          }, likeData)
            .then(function (res) {
              if (res['self:community_api:community:like']['ret'] != 0) {
                modal.toast(res['self:community_api:community:like']['msg']);
                that.data.commentList[data.index]['likeTabFlag'] = 0;
                that.setData({
                  commentList: that.data.commentList
                });
                return false;
              }
              if (data.type != 1) {
                that.data.commentList[data.index]['myLike'] = 0;
                that.data.commentList[data.index]['likeCount'] -= 1;
                that.data.commentList[data.index]['likeTabFlag'] = 0;
              } else {
                that.data.commentList[data.index]['myLike'] = 1;
                that.data.commentList[data.index]['likeCount'] += 1;
                that.data.commentList[data.index]['likeTabFlag'] = 0;
              }
              that.setData({
                commentList: that.data.commentList
              });
            })
        }

        //删除一级评论
        function delStairComment(delData) {
          if (mark != 0) {
            return false;
          }
          mark = delData['commentid'];
          var data = {
            'self:community_api:community:deleteComment': {
              'commentId': delData['commentid'],
              'articleId': 0,
              'timestamp': timestamp['timestamp'],
              'gtk': timestamp['gtk']
            }
          }
          request.post({
            path: '/wxapp_api/api'
          }, data)
            .then(function (res) {
              if (res['self:community_api:community:deleteComment']['ret'] != 0) {
                modal.toast(res['self:community_api:community:deleteComment']['msg']);
                return false;
              }
              that.data.articleInfo.commentCount -= (that.data.commentList[delData.index].commentCount + 1);
              that.data.articleInfo.firstCommentCount -= 1;
              that.data.commentList.splice([delData.index], 1);
              that.setData({
                articleInfo: that.data.articleInfo,
                commentList: that.data.commentList
              });
              mark = 0;
            })
        }

        // 删除按钮展示
        function delcommentFun(data) {
          for (var i = 0; i < that.data.commentList.length; i++) {
            var commentInfo = that.data.commentList[i]['secondCommentInfo']['commentInfo'];
            if (commentInfo) {
              for (var j = 0; j < commentInfo.length; j++) {
                commentInfo[j]['isDel'] = true;
              }
            }
          }
          that.data.commentList[data.parentidx]['secondCommentInfo']['commentInfo'][data.itemidx]['isDel'] = false;
          that.setData({
            commentList: that.data.commentList,
            removeBindtap: 1
          });

        }

        //删除按钮隐藏
        function removeBindtapFun(removeFlag) {
          if (removeFlag.removebindtap == 1) {
            for (var i = 0; i < that.data.commentList.length; i++) {
              var commentInfo = that.data.commentList[i]['secondCommentInfo']['commentInfo'];
              if (commentInfo) {
                for (var j = 0; j < commentInfo.length; j++) {
                  commentInfo[j]['isDel'] = true;
                }
              }
            }
            that.setData({
              commentList: that.data.commentList,
              removeBindtap: 0
            });
          }
        }

        //删除二级评论
        function delSecondComment(delSecondData) {
          if (mark != 0) {
            return false;
          }
          mark = delSecondData['commentid'];
          var data = {
            'self:community_api:community:deleteComment': {
              'commentId': delSecondData['commentid'],
              'articleId': 0,
              'timestamp': timestamp['timestamp'],
              'gtk': timestamp['gtk']
            }
          };
          request.post({
            path: '/wxapp_api/api'
          }, data)
            .then(function (res) {
              if (res['self:community_api:community:deleteComment']['ret'] != 0) {
                modal.toast(res['self:community_api:community:deleteComment']['msg']);
                return false;
              }
              that.data.commentList[delSecondData.index]['secondCommentInfo']['commentInfo'].splice([delSecondData.itemindex], 1);
              that.data.commentList[delSecondData.index]['commentCount'] -= 1;          
              that.data.articleInfo.commentCount -= 1;
              that.setData({
                articleInfo: that.data.articleInfo,
                commentList: that.data.commentList
              });
              mark = 0;
            });
        };
    },
    data: {
        flag:1,
        shipping_id:'',
        shipping:'',
        detailData: {},
        aDetails:[],
        aProductParams:[],
        commonwealData: {},
        commentListData: {},
        commentUrl:{},
        activeShow:false,
        activeFlag:'0',
        actionSheetFlag: '',
        cartCount:0,
        phone:[],
        isShowIdentification:false,
        isDonate:false,
        showTabIndex: 0, // 显示tab
        commentCountPerPage: 10, //一页评论数量
        loadStatus: 0, //是否正加载，防止重复加载
        nextPage: 1, //下一页评论页码
        hasNext: 1, //是否还有更多评论
        commentList: [], //评论列表
        articleId: 0, // 文章id
        actId: 0,
        medalMaskFlag: false,
        showTip: false // 是否显示提示 false:不显示
    },
    onLoad: function(options) {
        app.globalData.cartDetailCount = false;
        var tip = wx.getStorageSync('catchTipInfo') || false; // 存储是否点击过关闭
        var id = options.act_id;
        this.setData({
          actId: id
        })
        var that = this;

        // 如果当前时间大于设定的时间或者已点击过关闭
        if(new Date().getTime() >= new Date('2018/2/24 00:00:00').getTime() || tip) {
          that.setData({
            showTip: false
          });
        }else{
          that.setData({
            showTip: true
          });
        }

        that['data']['flag'] = options.flag;
        /*评论列表数据*/
        var commentListData = that.data['commentListData'];
        var commentUrl = that.data['commentUrl'];
        /*为组件填充数据*/
        var tempSwiper = this.data['wiiSwiper'];

        var tempActionSheet = this.data['wiiActionSheet'];
        var detailData = this.data['detailData'];
//      actionSheetOption = tempActionSheet;
        commentUrl.act_id = id;
        //设置公益初始值
        that.data.commonwealData['isShowCommonweal'] = false;
        that.setData({
            'actId':id
        });
        
        request.post({
            path: '/wxapp_api/api'
        },{"dp:api:act:detail":{"id":id}})
            .then(function(res){
                detailData = res['dp:api:act:detail'];
                // detailData = mockDetail['data']['dp:api:act:detail'];
                commentUrl.img = detailData.data.act_img_url.split(',')[0];
                commentUrl.tit = detailData.data.commodity_name;

                if(detailData.ret != '0'){
                    // modal.toast(detailData.msg);
                    wx.navigateTo({
                        url: "../error/error"
                    })
                    return false;
                }
                var commentListData = detailData.data.commentList;
                //格式化url
                function escape2Html(str) {
                    var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
                    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
                }
                if(commentListData.length != 0){
                    for(var i=0,len=commentListData.commentList.length; i<len; ++i){
                        var str = commentListData.commentList[i].userInfo.face;
                        commentListData.commentList[i].userInfo.face = escape2Html(str);
                    }    
                }
                
                //活动是否在有效时间内
                var nowTime = Date.parse(new Date());
                var actStartTime = Date.parse(detailData.data.act_start_time.replace(/-/g,"/"));
                var actEndTime = Date.parse(detailData.data.act_end_time.replace(/-/g,"/"));
                if(nowTime >= actStartTime && nowTime <= actEndTime){
                    that.setData({
                        activeShow : true,
                        activeFlag : '1'
                    });
                }
                //活动未开始
                if(nowTime <= actStartTime){
                    that.setData({
                        activeShow : false,
                        activeFlag : '2'
                    })
                }
                 //活动已结束
                if(nowTime >= actEndTime){
                    that.setData({
                        activeShow : false,
                        activeFlag : '3'
                    })
                }
                var bannerList = detailData.data.act_img_url;
                var specList = detailData.data.act_spec;

                bannerList = bannerList.split(',');
                specList = specList.split(';');

                // 保存规格字段的字符串
                var specArr = detailData.data.act_spec.split(';');

                for(var i=0,len=bannerList.length; i<len; ++i){
                    tempSwiper['data'].push({'pic':bannerList[i]});
                }
                for(var i=0,len=specList.length; i<len; ++i){
                    specList[i] = specList[i].split(',');
                }

                // 设置规格名称
                detailData.data['act_spec'] = specList[0][1];
                // 规格插件数据整理
                tempActionSheet['data'] = {
                    isShow:false,
                    onePrice: specList[0][2],
                    prePrice: specList[0][3],
                    skuList:[],
                    choosedSku:{
                        id:specList[0][0],
                        name: specList[0][1],
                        imgUrl: bannerList[0],
                        price: specList[0][2],
                        prePrice: specList[0][3],
                        minNumber: 1,
                        maxNumber: specList[0][4],
                        stock : specList[0][4],
                        info: specArr[0]
                    },
                    hasCart:true
                };
                // 组件升级，counter结构变化；author: yimeilu
                tempActionSheet['counter']['wiiCounter']['data'] = {
                    isMin: true,
                    isMax: false,
                    countNumber: 1,
                    minNumber: 1,
                    maxNumber: specList[0][4],
                    numberUnit: 1
                };

                // 规格数据中的list数据
                for(var i=0,len=specList.length; i<len; ++i){
                    tempActionSheet['data']['skuList'].push({
                        id:specList[i][0],
                        name: specList[i][1],
                        imgUrl: bannerList[0],
                        price: specList[i][2],
                        prePrice: specList[i][3],
                        minNumber: 1,
                        maxNumber: specList[i][4],
                        stock: specList[i][4],
                        info: specArr[i]
                    });
                }

                function isJSON(str) {
                    if (typeof str == 'string') {
                        try {
                            JSON.parse(str);
                            return true;
                        } catch(e) {
                            console.log(e);
                            return false;
                        }
                    }   
                }

                function TransferString(content) {  
                    var str = content;  
                    try{  
                         str = str.replace(/<br \/>/g, "\n")
                         str = str.replace(/&nbsp;/g, " ")
                    }catch(e) {  
                        console.log(e.message);  
                    }  
                    return str;  
                } 

                var aDetails = [];

                if(isJSON(detailData['data']['act_details'])){
                    var details = JSON.parse(detailData['data']['act_details']);
                    for (var i in details){
                        var oDetails = {};                    
                        oDetails.title = i;
                        for(var a = 0 ; a<details[i].length;a++){
                            details[i][a]['info'] = TransferString(details[i][a]['info']);
                        }
                        oDetails.concent = details[i];
                        aDetails.push(oDetails);
                    }
                }

                var aProductParams = [];
                var phone = [];
                
                if(isJSON(detailData['data']['product_params'])){
                    var oProductParams=JSON.parse(detailData['data']['product_params']);
                    for (var s in oProductParams){
                        var newOProductParams = {};
                        if(s == '客服电话'){
                            phone = oProductParams[s].split('/');
                        }
                        newOProductParams.title = s;
                        newOProductParams.content = oProductParams[s];
                        aProductParams.push(newOProductParams);
                    }
                    
                }
                if(detailData['data']['shipping_id'] == undefined){
                    detailData.data.shipping_id = '1';
                    detailData.data.shipping = '0'; 
                }
                that.setData({
                    wiiSwiper:tempSwiper,
                    wiiActionSheet:tempActionSheet,
                    detailData: detailData,
                    aDetails:aDetails,
                    aProductParams:aProductParams,
                    shipping_id:detailData['data']['shipping_id'],
                    shipping:detailData['data']['shipping'],
                    commentListData:commentListData,
                    commentUrl:commentUrl,
                    phone:phone
                });
                var option = {
                  articleId: that.data.detailData.data.act_comment_id,
                  page: that.data.nextPage
                };
                that.setData({
                    articleId: that.data.detailData.data.act_comment_id
                })
                //加载完评论后，附带需要渲染的数据
                var setData = {
                    detailData: that.data.detailData
                }
                that.loadComment(option, setData);
                modal.hide();
        });
        request.post({
            path: '/wxapp_api/api'
        },{'self:cart_api:cart:cartcount':{}})
        .then(function(res){
            var cartData = res['self:cart_api:cart:cartcount'];
            if(cartData.ret != '0'){
                // modal.toast(cartData.msg);
                wx.navigateTo({
                    url: "../error/error"
                })
                return false;
            }
            that.setData({
                cartCount : cartData.data
            });
        });
       
    },
    onShow : function(e){
        var that = this;
        if(app.globalData.cartDetailCount){
            app.globalData.cartDetailCount = false;
            request.post({
                path: '/wxapp_api/api'
            },{'self:cart_api:cart:cartcount':{}})
            .then(function(res){
                var cartData = res['self:cart_api:cart:cartcount'];
                if(cartData.ret != '0'){
                    // modal.toast(cartData.msg);
                    wx.navigateTo({
                        url: "../error/error"
                    })
                    return false;
                }
                that.setData({
                    cartCount : cartData.data
                });
            });
        }
    },
    showActionSheet: function(e) {
        this.wiiShowActionSheet(e)
    },
    showSelfActionSheet:function(e){
        this.setData({
            'wiiActionSheet.data.isShow':true
        });
    },
    goCartPage: function(e) {
        request.bind().then(() => {
            wx.navigateTo({
                url: '../shopping-cart/shopping-cart'
            })
        })
    },
    onShareAppMessage:function(){
        var that = this;
        if(that.data.detailData.data.sales_form==1){
            return{
                title: that.data.detailData.data. offline_share_title,
                imageUrl:that.data.detailData.data.offline_share_pic,
                path: that.data.detailData.data.offline_share_link
            }
        }else{
           return {
            title: that.data.detailData.data.share_title,
            desc:that.data.detailData.data.share_detail,
            path: '/pages/detail/detail?flag=0&act_id='+ that.data.actId
          } 
        }
        
    },
    showCommonwealInfo:function(){
        //弹出公益商品的弹窗；
        var that = this;
        var c = that.data.commonwealData;
        c.isShowCommonweal = true;
        this.setData({
            commonwealData : c
        });
    },
    hideCommonwealInfo:function(){
        //关闭公益商品的弹窗；
        var that = this;
        var c = that.data.commonwealData;
        c.isShowCommonweal = false;
        this.setData({
            commonwealData : c
        });
    },
    showMedalMask: function(){
      this.setData({
          medalMaskFlag : true
      });
    },
    hideMedalMask: function(){
      this.setData({
          medalMaskFlag : false
      });
    },
    callPhoneFn: function(e){
        var phone = e.target.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone //仅为示例，并非真实的电话号码
        })
    },
    showIdentificationInfo: function(){
        this.setData({
            isShowIdentification : true
        });
    },
    hideIdentificationInfo: function(){
        this.setData({
            isShowIdentification : false
        });
    },
    showDonateInfo: function(){
        this.setData({
            isDonate : true
        });
    },
    hideDonateInfo: function(){
        this.setData({
            isDonate : false
        });
    },
    changeTab: function(e){
        var showTabIndex = this.data['showTabIndex'];
        var index = e.target.dataset.index;
        if (index == 0 || this.data.detailData.data.act_comment_count > 0) {
            this.setData({
                showTabIndex : index
            })    
        }
    },
    loadComment: function (option, setData, refresh) {
        var that = this;
        if (setData == undefined) {
          setData = {};
        }
        option.pageSize = that.data.commentCountPerPage;
        //开始加载
        that.data.loadStatus = 1;
        request.post({
          path: '/wxapp_api/api'
        }, { "self:community_api:community:commentList": option }).then(function (resp) {
          if (resp['self:community_api:community:commentList'].ret == 0) {
            var respData = resp['self:community_api:community:commentList'].data;
            //结束加载
            that.data.loadStatus = 0;
            setData.loadStatus = that.data.loadStatus;
            //文章信息
            that.data.articleInfo = respData.articleInfo;
            setData.articleInfo = that.data.articleInfo;
            //下页页码
            that.data.nextPage = respData.page + 1
            setData.nextPage = that.data.nextPage;
            //是还有一页
            that.data.hasNext = respData.hasNext;
            setData.hasNext = that.data.hasNext;
            //评论列表        
            if (refresh != undefined && refresh == true) { //重新刷评论列表
              that.data.commentList = [];
              setData.tabIndex = 1; //切到留言列表
            }
            for (var i = 0; i < respData.commentList.length; i++) {
              respData.commentList[i]['userInfo']['face'] = filter.filter(respData.commentList[i]['userInfo']['face']);
              respData.commentList[i]['content'] = filter.filter(respData.commentList[i]['content']);
              respData.commentList[i]['createTime'] = formatTime.formatTime(respData.commentList[i]['createTime']);
              respData.commentList[i]['likeTabFlag'] = 0;
              that.data.commentList.push(respData.commentList[i]);
            }
            setData.commentList = that.data.commentList;
            //渲染数据           
            that.setData(setData);
          } else {
            modal.toast(res['self:community_api:community:commentList'].msg);
          }
          // modal.hide();
        });
    },
    //滑动加载评论
    pullLoad: function () {
        var that = this;
        // modal.loading();
        if (that.data.showTabIndex == 1 && that.data.loadStatus == 0 && that.data.hasNext == 1) {//只有用户停留在留言列表且还有下一页且没有在加载才加载
          var option = {};
          option.articleId = that.data.articleId;
          option.page = that.data.nextPage;
          option.pageSize = that.data.commentCountPerPage;
          that.loadComment(option);
        }
    },
    // 关闭提示
    closeTipFn: function() {
      wx.setStorageSync('catchTipInfo', true);
      this.setData({
        showTip: false
      });
    }
};

//actionSheet = utils.assign(actionSheet, actionSheetOption);

utils.assign(pageSetting, swiper, actionSheet, comment, goTop);
Page(pageSetting);
